# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/14'
__author__ = 'Just'
__filename__ = 'comic'
"""
from sqlalchemy import Column, Integer, String, orm, or_, desc

from app.libs.error_code import NotFoundException
from app.model.base import BaseModel, db
from app.model.comic_latest import ComicLatest


class Comic(BaseModel):
    """漫画信息模型"""
    __tablename__ = 'comic'

    id = Column(Integer, primary_key=True, autoincrement=True)
    cid = Column(Integer, unique=True, nullable=False, comment='漫画id')
    title = Column(String(50), comment='漫画名称')
    category = Column(String(10), comment="漫画分类")
    area = Column(String(6), comment="地区")
    author = Column(String(10), comment='漫画作者')
    image = Column(String(255), comment='封面图')
    description = Column(String(255), comment='漫画简介')

    # 一对一 一部漫画只有一个更新条目
    updates = db.relationship('ComicLatest', uselist=False)
    # 一对多 一部漫画有很多章节
    sections = db.relationship('ComicSection',  backref='comic_section', lazy='dynamic')

    @orm.reconstructor
    def __init__(self):
        # 序列化列表
        self.fields = ['cid', 'title',
                       'category', 'area', 'author',
                       'image', 'description'
                       ]

    @staticmethod
    def fuzzy_search(q, start, limit):
        """模糊搜索 title=%q% or author=%q%"""
        comics = Comic.query.filter(
                        or_(Comic.title.like(q), Comic.author.like(q)), Comic.status == 1)
        total = comics.count()
        if start >= total:
            raise NotFoundException(msg='没有数据', error_code=3003)
        comics = comics.order_by().offset(start).limit(limit).all()
        return {"comics": comics, "start": start, "limit": limit, "total": total}

    @staticmethod
    def get_list(start, limit):
        """获取所有漫画列表"""
        comics = Comic.query.order_by(Comic.status == 1, desc(ComicLatest.update_time)).offset(start).limit(limit).all()
        total = comics.count()
        return {"comics": comics, "start": start, "limit": limit, "total": total}